import time
from rest_framework.views import APIView
from django.core.mail import send_mail
import copy
import random
from SecureHelperServer.settings import APP_NAME, formatResponseData, verificationCodeExpiredExecutorManager
from User.models import EmailVerificationRecord
from utils.conf import newID, Response
from utils.loggingConfig import logger
from utils.taskTools import Task


class SendVerificationCodeView(APIView):
    # 局部(本视图有效)身份认证
    authentication_classes = []
    # 局部(本视图有效)权限认证
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        发送验证码
        """
        data = copy.deepcopy(formatResponseData)
        try:
            email = request.data.get("email")

            if not email:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # 发送验证码
            verificationCode = random.randint(100000, 999999)
            send_mail(f'{APP_NAME} 登录验证', f'此次验证码为：{verificationCode}', '1274664300@qq.com', [email])

            # 存入验证记录
            emailVerificationRecord = EmailVerificationRecord(id=newID(), email=email,
                                                              verificationCode=verificationCode)
            emailVerificationRecord.save()

            # 异步进行邮箱过期处理
            task = Task(fun=verificationCodeExpired,
                        taskName=f"验证码过期任务：emailVerificationRecordId={emailVerificationRecord.id}")
            verificationCodeExpiredExecutorManager.putAndRunTask(task=task,
                                                                 emailVerificationRecordId=emailVerificationRecord.id)
            logger.info(f"发送验证码：启动验证码过期任务: emailVerificationRecordId={emailVerificationRecord.id}")

            data["data"]["emailVerificationRecordId"] = emailVerificationRecord.id
            return Response(data=data, responseMsg="验证码发送成功",
                            loggerMsg=f"发送验证码：发送成功: emailVerificationRecordId={emailVerificationRecord.id}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)


def verificationCodeExpired(emailVerificationRecordId):
    """
    邮箱验证码过期
    """

    # 60s过期时间
    time.sleep(60)

    emailVerificationRecord = EmailVerificationRecord.objects.filter(id=emailVerificationRecordId).first()

    if emailVerificationRecord:
        emailVerificationRecord.isValid = False
        emailVerificationRecord.save()
        logger.info(f"验证码有效期倒计时结束: emailVerificationRecordId={emailVerificationRecord.id}")
